package com.gmics.unifiq.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.gmics.android.R;
import com.gmics.unifiq.entity.Event;
import com.gmics.unifiq.entity.Group;

public class EventAdapter extends BaseAdapter {
	private Context context;
	private ArrayList<Event> eventArr;
	private ArrayList<Group> grpArr;

	public EventAdapter(Context context, ArrayList<Event> eventArr, ArrayList<Group> grpArr) {
		this.context = context;
		this.eventArr = eventArr;
		this.grpArr = grpArr;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return eventArr.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return eventArr.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return eventArr.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View listView = new View(context);
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		listView = inflater.inflate(R.layout.event_list_item, null);
		
		ImageView img = (ImageView) listView
				.findViewById(R.id.event_grp_img);
		TextView title = (TextView) listView.findViewById(R.id.title_tv);
		TextView desc = (TextView) listView.findViewById(R.id.desc_tv);

		title.setText(eventArr.get(position).getName());
		desc.setText(eventArr.get(position).getDescription());

		int a = 0;
		for (int i = 0; i < grpArr.size(); i++){
			if (eventArr.get(position).getGroupID() == grpArr.get(i).getGroupID()){
				a = i;
				break;
			}
		}
		
		try {
			Bitmap bitmap = BitmapFactory
					.decodeStream((InputStream) new URL(grpArr.get(a).getImagePath()).getContent());
			img.setImageBitmap(bitmap);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return listView;
	}

}